for-of loop
Loop with a string
with index
let message = 'hello';
for( let i in message ) {
console.log( message[i] );
}
with element
let message = 'hello';
for( let ch of message ) {
console.log( ch );
}
UTF-32 support
The for-of loop handles UTF-32 characters properly. The for-in loop interprets them as two byte long characters.
let text = '\u{1F601}\u{1F43C}';
console.log( 'text: ', text );
// for-in can not work with UTF-32 characters!!!!
for( let i in text ) {
console.log(text[i]);
};
// but for-of works.
for ( let c of text ) {
console.log( c );
};
Destructuring and the DOM in the for-of loop
let flights = [
{ source: 'Dublin', destination: 'Warsaw' },
{ source: 'New York', destination: 'Phoenix' }
];
for ( let { source, destination } of flights ) {
console.log( source, destination );
}
// output:
// Dublin Warsaw
// New York Phoenix
The for-loop and the DOM#
let divs = document.querySelectorAll( 'div' );
for ( let div of divs )
{
let rand = Math.floor ( Math.random() * 3 );
div.style.color = [ '#990000', '#009900', '#000099'][ rand ];
}